package com.decheng.service.impl;

import com.decheng.dao.BookDao;
import com.decheng.dao.impl.BookDaoImpl;
import com.decheng.dto.PaginationDTO;
import com.decheng.pojo.Book;
import com.decheng.service.BookService;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 */
public class BookServiceImpl implements BookService {

    private BookDao bookDao = new BookDaoImpl();

    @Override
    public ArrayList<Book> showBookList() {
        return bookDao.getAllBooks();
    }

    /**
     * 显示图书列表-分页
     *
     * @param currentPage
     * @param pageSize
     */
    @Override
    public PaginationDTO<Book> showBookList(String currentPage, String pageSize) {
        // 1. 检查数据是否有效
        if (StringUtils.isEmptyOrWhitespace(currentPage)) {
            // 当前页为空，默认查询第一页
            currentPage = "1";
        }
        if (StringUtils.isEmptyOrWhitespace(pageSize)) {
            // 页面大小为空，设置默认页面大小
            pageSize = "10";
        }
        // 2. 查询数据总数
        Long count = bookDao.count();
        // 3. 转换数据类型
        Integer currentPageInt = Integer.valueOf(currentPage);
        Integer pageSizeInt = Integer.valueOf(pageSize);
        // 3. 检查当前页是否符合规范
        if (currentPageInt > count / pageSizeInt) {
            // 4. 不符合规范，设置默认值
            currentPageInt = 1;
            pageSizeInt = 10;
        }
        ArrayList<Book> books = bookDao.getAllBooksPagination(currentPageInt, pageSizeInt);
        PaginationDTO<Book> bp = new PaginationDTO<>();
        bp.setList(books);
        bp.setCurrentPage(currentPageInt);
        bp.setTotalCount(bookDao.count());
        bp.setPageSize(pageSizeInt);
        return bp;
    }


    @Override
    public void removeBook(Integer id) {
        Book book = new Book();
        book.setBookId(id);
        bookDao.removeBookById(book);
    }

    /**
     * 添加图书
     *
     * @param book
     */
    @Override
    public void addBook(Book book) {
        bookDao.addBook(book);
    }

    /**
     * 查询图书
     *
     * @param book
     * @return
     */
    @Override
    public Book getBook(Book book) {
        return bookDao.getBookById(book);

    }

    /**
     * 更新图书
     *
     * @param book
     */
    @Override
    public void updateBook(Book book) {
        bookDao.updateBookById(book);
    }
}
